package cn.luo.uilt;

import cn.luo.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class SessionUitls {

    //获取用户信息 session
    public static User getUser(){
        SecurityContext context = SecurityContextHolder.getContext();
        //登录成功获取 Authentication
        Authentication authentication = context.getAuthentication();
        //User user = (User) session.getAttribute("user");
        User user = (User) authentication.getPrincipal();
        return user;
    }

    public static Object getUser1() {
        Object principal =  SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("UserInformation-->principal = " + principal);
        if (principal == null ) return null;
        if (principal instanceof UserDetails) {
            return principal;
        }else {
            return String.valueOf(principal);
        }
    }

    public static String getUid(){
        User user = getUser();
        if (user == null) {
            return null;
        }
        return user.getId();
    }

    public static String getNickname(){
        User user = getUser();
        if (user == null) {
            return null;
        }
        return user.getNickname();
    }
}
